const app = getApp();
Page({
  data: {
    hasList: false,          // 列表是否有数据
    totalPrice: 0,           // 总价，初始为0
    selectAllStatus: true ,  // 全选状态，默认全选
    sum:0,
    openid: '',
    items: [],
    startX: 0, //开始坐标
    startY: 0,
    delData:false,
    arrData:0,
    StatusBar: app.globalData.StatusBar, //模态动画
    CustomBar: app.globalData.CustomBar,
    moRenShop: ""
  },
  //模态动画
  showModal(e){
    this.setData({
      modalName: e.currentTarget.dataset.target
    })
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },
  // 计算总价
  getTotalPrice:function(){
    let items = this.data.items;// 获取购物车列表
    let total = 0;
    for (let i = 0; i < items.length; i++){// 循环列表得到每个数据
      if (items[i].selected){//判断选中才会计算价格
        total += items[i].goods_num * items[i].goods_present_price;// 所有价格加起来
      }
    }
    this.setData({// 最后赋值到data中渲染到页面
      items: items,
      totalPrice: total.toFixed(2)
    });
  },
  //删除购物车
  delData:function(e){
    var that = this;
    var delData = that.data.delData;
    var data = that.data.items;
    var goods_num = 0;
    for (var i = 0; i < data.length;i++){
      goods_num += data[i]['goods_num'];
      data[i]['selected'] = true;
    }
    that.setData({
      sum: goods_num,
      selectAllStatus: true,
      items: data,
      delData: !delData
    })
    app.globalData.sum = goods_num
    // console.log(app.globalData.sum)
    
    that.getTotalPrice();
  },
  delAll:function(e){
    var that = this;
    var data = that.data.items;
    var arr = new Array();
    var arrs = new Array();
    var str = '';
    for(var i=0;i<data.length;i++){
      if(data[i]['selected'] === false){
        arr.push(data[i]);
      }
      if(data[i]['selected'] === true){
        str += data[i]['id'] + ',';
      }
    }
    var goods_num = 0;
    for (var i = 0; i < arr.length; i++) {
      goods_num += arr[i]['goods_num'];
      arr[i]['selected'] = true;
    }
    that.setData({
      sum: goods_num,
      items: arr
    })
    app.globalData.sum = goods_num
    // console.log(app.globalData.sum)
    that.getTotalPrice();
    str = str.slice(0, str.length - 1);
    arrs = str.split(',');
    if (arrs.length >=2){
      var style = 2;
    }else{
      var style = 1;
    }

    const value = wx.getStorageSync('openid');
    app.util.request({
      url: 'admin/WxGoodsApi/deleteShopcarGoods',
      method: 'post',
      data: {
        uid: value,
        type: style,
        id: str
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        if (res.data.code == 0){
          that.hideModal(e)
          that.setData({
            items: arr,
            selectAllStatus: true,
            delData: false
          })
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 2000
          })
          app.globalData.tabbar.list[2]['dott'] = goods_num;
          app.setData();
        }
      },
      fail: function (res) {
        wx.showToast({
          title: "服务器响应失败",
          icon: 'none',
          duration: 2000
        })
      }
    });
  },
  // icon选择事件
  selectList(e) {
    var that = this;
    const index = e.currentTarget.dataset.index;    // 获取data- 传进来的index
    let items = this.data.items;                    // 获取购物车列表
    const selected = items[index].selected;         // 获取当前商品的选中状态
    var goods_num = that.data.sum;
    var selectAllStatus = that.data.selectAllStatus;
    var style = '';
    
    if(selected){
      items[index].selected = !selected;
      goods_num = goods_num - items[index].goods_num;
      that.setData({
        selectAllStatus: false
      })
    }else{
      items[index].selected = !selected;
      goods_num = goods_num + items[index].goods_num;
      for(var i = 0; i < items.length;i++){
        style += items[i]['selected']+',';
      } 
      style = style.slice(0, style.length - 1);
      if(style.indexOf(false) === -1){
        that.setData({
          selectAllStatus:true
        })
      }else{
        that.setData({
          selectAllStatus: false
        })
      }
    }
    that.setData({
      sum: goods_num,
      items: items
    });
    app.globalData.sum = goods_num
    // console.log(app.globalData.sum)
    that.getTotalPrice();
  },
  // 输入框事件
  inputTyping:function(e){
    var that = this;
    var reg = /^[1-9]\d*$/;
    var num = e.detail.value;
    var index = e.target.dataset.index;
    var data = that.data.items;
    if (reg.test(e.detail.value)) {
      var sku = data[index]['sku'];
      if (num > sku){
        data[index]['goods_num'] = sku;
      }else{
        data[index]['goods_num'] = num;
      }
      that.setData({
        items: data
      })
      var items = that.data.items;
      var nums = 0;
      for (var i=0;i<items.length;i++){
        items[i]['goods_num'] = parseInt(items[i]['goods_num']);
        nums += items[i]['goods_num'];
      }
      that.setData({
        sum: nums
      })
      app.globalData.sum = nums
      // console.log(app.globalData.sum)
      that.getTotalPrice();
    }else{
      data[index]['goods_num'] = 1;
      that.setData({
        items:data
      })
      var items = that.data.items;
      var nums = 0;
      for (var i = 0; i < items.length; i++) {
        items[i]['goods_num'] = parseInt(items[i]['goods_num']);
        nums += items[i]['goods_num'];
      }
      that.setData({
        sum: nums
      })
      app.globalData.sum = nums
      // console.log(app.globalData.sum)
      that.getTotalPrice();
    }

    // 修改购物车商品数量
    const value = wx.getStorageSync('openid');
    app.util.request({
      url: 'admin/WxGoodsApi/updateShopcarGoodsNum',
      method: 'post',
      data: {
        uid: value,
        id:data[index].id,
        goods_num:data[index]['goods_num']
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        // console.log(res)
        if (res.data.code == 0) {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 2000
          })
          app.globalData.tabbar.list[2]['dott'] = data[index]['goods_num'];
          app.setData();
        }
      },
      fail:function(res){
        wx.showToast({
          title: "服务器响应失败",
          icon: 'none',
          duration: 2000
        })
      }
    });
  },
  // 增加数量
  addCount(e){
    var that = this;
    const index = e.currentTarget.dataset.index;
    let items = that.data.items;
    var data = items[index]['goods_num'];
    var goods_num = that.data.sum;
    if (items[index]['sku'] === data){
      items[index]['goods_num'] = items[index]['sku'];
    }else{
      items[index]['goods_num'] = data + 1;
      goods_num = goods_num + 1;
    }
    // 修改购物车商品数量
    const value = wx.getStorageSync('openid');
    app.util.request({
      url: 'admin/WxGoodsApi/updateShopcarGoodsNum',
      method: 'post',
      data: {
        uid: value,
        id: items[index]['id'],
        goods_num: items[index]['goods_num']
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res){
        if (res.data.code == 0){
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 2000
          })
          app.globalData.tabbar.list[2]['dott'] = items[index]['goods_num'];
          app.setData();
        }
      },
      fail: function (res) {
        wx.showToast({
          title: "服务器响应失败",
          icon: 'none',
          duration: 2000
        })
      }
    });
    that.setData({
      sum: goods_num,
      items: items
    });
    app.globalData.sum = goods_num
    // console.log(app.globalData.sum)
    that.getTotalPrice();
  },
  // 减少数量
  minusCount(e){
    var that = this;
    const index = e.currentTarget.dataset.index;
    let items = that.data.items;
    var data = items[index]['goods_num'];
    var goods_num = that.data.sum;
    if(data === 1){
      items[index]['goods_num'] = 1;
    }else{
      items[index]['goods_num'] = data - 1;
      goods_num = goods_num - 1;
    }
    if (goods_num <= 1) {
      return false;
    }
    // 修改购物车商品数量
    const value = wx.getStorageSync('openid');
    app.util.request({
      url: 'admin/WxGoodsApi/updateShopcarGoodsNum',
      method: 'post',
      data: {
        uid: value,
        id: items[index]['id'],
        goods_num: items[index]['goods_num']
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        if (res.data.code == 0) {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 2000
          })
          app.globalData.tabbar.list[2]['dott'] = items[index]['goods_num'];
          app.setData();
        }
      },
      fail: function (res) {
        wx.showToast({
          title: "服务器响应失败",
          icon: 'none',
          duration: 2000
        })
      }
    });
    that.setData({
      sum: goods_num,
      items: items
    });
    app.globalData.sum = goods_num
    // console.log(app.globalData.sum)
    that.getTotalPrice();
  },
  // 全选事件
  selectAll(e) {
    var that = this;
    let selectAllStatus = that.data.selectAllStatus;
    var data = that.data.items;
    var sum = 0;
    if(!selectAllStatus){
      for (var i = 0; i < data.length; i++) {
        sum += data[i]['goods_num'];
      }
    }else{
      sum = 0;
    }
    selectAllStatus = !selectAllStatus;
    let items = that.data.items;
    for (let i = 0; i < items.length; i++){
      items[i].selected = selectAllStatus;
    }
    that.setData({
      selectAllStatus: selectAllStatus,
      sum: sum,
      items: items
    });
    app.globalData.sum = goods_num
    // console.log(app.globalData.sum)
    that.getTotalPrice();
  },
  // 判断购物车有一个没被选中 全选取消

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const value = wx.getStorageSync('openid');
    // 默认门店
    wx.getLocation({
      type: 'wgs84',
      success(res) {
        const latitude = res.latitude
        const longitude = res.longitude
        app.util.request({
          url: 'admin/WxGoodsApi/nearby_store',
          data: {
            uid: value,
            longitude: latitude,
            latitude: longitude
          },
          method: 'post',
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          success: function (res) {
            if (res.data.code == 0) {
              var data = res.data.data;
              for (var c = 0; c < data.length; c++) {
                if (data[c].default_shop === 1) {
                  that.setData({
                    moRenShop: data[c].shop_name,
                    // shop_id: data[c].id
                  })
                }
              }
              if (that.data.moRenShop == "") {
                that.setData({
                  moRenShop: data[0].shop_name,
                  // shop_id: data[0].id
                })
              }
            }

          },
          fail: function (res) {
            wx.showToast({
              title: '服务器响应失败',
              icon: 'none',
              duration: 2000
            })
          }
        });
      }
    });
    var that = this;
    app.changeTabBar();
    wx.setNavigationBarTitle({
      title: '购物车'
    });
    // 显示购物车列表
    app.util.request({
      url: 'admin/WxGoodsApi/shopcarList',
      method: 'post',
      data: {
        uid: value,
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res){
        console.log(res)
        if(res.data.code==0){
          var datalun = res.data.data;
          for (var i = 0; i < datalun.length; i++){
            datalun[i]['selected'] = true;
            datalun[i]['goods_image'] = app.globalData.url + datalun[i]['goods_image'];
          }
          if (res.data.code == 0){
            var data = datalun;
            var goods_num = 0;
            for (var i = 0; i < data.length; i++) {
              goods_num += data[i]['goods_num'];
            }
            that.setData({
              sum: goods_num,
              items: datalun
            })
            app.globalData.sum = goods_num
            // console.log(app.globalData.sum)
            that.getTotalPrice();
          }
        }
      }
    });
    
  },
  // 结算
  jieSuan:function(e){
    var that = this;
    const value = wx.getStorageSync('openid')
    var form_id = e.detail.formId
    app.util.request({
      url: 'admin/WxGoodsApi/formId',
      method: 'post',
      data: {
        form_id: form_id,
        open_id: value
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        console.log(res)
        if (res.data.code == 0) {
          console.log("formId发送成功")
        }

      },
      fail: function (res) {
        wx.showToast({
          title: '服务器响应失败',
          icon: 'none',
          duration: 2000
        })
      }
    });
    var data = that.data.items;
    var strJie = '';
    for (var i = 0; i < data.length; i++) {
      if (data[i]['selected'] === true) {
        strJie += data[i]['id'] + ',';
      }
    } 
    strJie = strJie.slice(0, strJie.length - 1);
    // console.log(strJie)
    var shopcar_id=strJie
    wx.navigateTo({
      url: '../index/XSMSIntegralExchange?shopcar_id='+shopcar_id
    })



  },
  //手指触摸动作开始 记录起点X坐标
  // touchstart: function (e) {
  //   //开始触摸时 重置所有删除
  //   this.data.items.forEach(function (v, i) {
  //     if (v.isTouchMove)//只操作为true的
  //       v.isTouchMove = false;
  //   })
  //   this.setData({
  //     startX: e.changedTouches[0].clientX,
  //     startY: e.changedTouches[0].clientY,
  //     items: this.data.items
  //   })
  // },
  //滑动事件处理
  // touchmove: function (e) {
  //   var that = this,
  //     index = e.currentTarget.dataset.index,//当前索引
  //     startX = that.data.startX,//开始X坐标
  //     startY = that.data.startY,//开始Y坐标
  //     touchMoveX = e.changedTouches[0].clientX,//滑动变化坐标
  //     touchMoveY = e.changedTouches[0].clientY,//滑动变化坐标
  //     //获取滑动角度
  //     angle = that.angle({ X: startX, Y: startY }, { X: touchMoveX, Y: touchMoveY });
  //   that.data.items.forEach(function (v, i) {
  //     v.isTouchMove = false
  //     //滑动超过30度角 return
  //     if (Math.abs(angle) > 30) return;
  //     if (i == index) {
  //       if (touchMoveX > startX) //右滑
  //         v.isTouchMove = false
  //       else //左滑
  //         v.isTouchMove = true
  //     }
  //   })
  //   //更新数据
  //   that.setData({
  //     items: that.data.items
  //   })
  // },
  /**
   * 计算滑动角度
   * @param {Object} start 起点坐标
   * @param {Object} end 终点坐标
   */
  angle: function (start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y
    //返回角度 /Math.atan()返回数字的反正切值
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
  },
  //删除事件
  del: function (e) {
    var that=this
    that.hideModal()
    this.data.items.splice(e.currentTarget.dataset.index, 1)
    this.setData({
      items: this.data.items
    })
    
  },

 

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function(){
    const value = wx.getStorageSync('openid');
    app.util.request({
      url: 'admin/WxGoodsApi/shopcarList',
      method: 'post',
      data: {
        uid: value
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        var data = res.data.data;
        var num = 0;
        if (data === undefined || data.length == 0) {
          app.globalData.tabbar.list[2]['dott'] = num;
          app.setData();
        } else {
          for (var i = 0; i < data.length; i++) {
            num += data[i]['goods_num'];
          }
          app.globalData.tabbar.list[2]['dott'] = num;
          app.setData();
        }
      },
      fail: function (res) {
        wx.showToast({
          title: '服务器响应失败',
          icon: 'none',
          duration: 2000
        })
      }
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})